#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"

/*队列：MailBox*/

void writeTask(void *pvParameters)
{
    // 队列句柄
    QueueHandle_t MailBox;
    MailBox = (QueueHandle_t)pvParameters;

    // 发送状态
    BaseType_t xStatus;
    int i = 0;

    while (1)
    {
        xStatus = xQueueOverwrite(MailBox, &i); // 注意这里传入的还是指针地址
        if (xStatus == pdPASS)
        {
            // 成功发送
            printf("writeTask: %d\n", i);
        }
        else
        {
            // 发送失败
            printf("writeTask: failed\n");
        }
        // xUSB.id++;
        // xUSB.data++;
        i++;
        vTaskDelay(pdMS_TO_TICKS(6000));
    }
}

void readTask(void *pvParameters)
{
    // 队列句柄
    QueueHandle_t MailBox;
    MailBox = (QueueHandle_t)pvParameters;

    // 发送状态
    BaseType_t xStatus;
    int i = 222;

    while (1)
    {
        // xQueuePeek从队列中取出数据，但是不删除数据
        xStatus = xQueuePeek(MailBox, &i, portMAX_DELAY); // 0 如果没有数据，则立即返回；如果是portMAX_DELAY，则阻塞等待
        if (xStatus == pdPASS)
        {
            // 成功发送
            printf("readTask: %d\n", i);
        }
        else
        {
            // 发送失败
            printf("readTask: failed\n");
        }

        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

void app_main(void)
{
    QueueHandle_t MailBox;                  // MailBox还是一个普通的QueueHandle_t
    MailBox = xQueueCreate(1, sizeof(int)); // 邮箱大小为1，每个数据为int类型

    if (MailBox != NULL)
    {
        printf("QHandle is not NULL\n");
        xTaskCreate(writeTask, "sendTask", 2048, (void *)MailBox, 1, NULL);
        xTaskCreate(readTask, "readTask1", 2048, (void *)MailBox, 2, NULL);
        xTaskCreate(readTask, "readTask2", 2048, (void *)MailBox, 2, NULL);
        xTaskCreate(readTask, "readTask3", 2048, (void *)MailBox, 2, NULL);
    }
    else
    {
        printf("QHandle is NULL\n");
    }
}
